package com.mayuanfei.springboot14.controller;

import cn.hutool.json.JSONUtil;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.map.IMap;
import com.mayuanfei.springboot14.common.Constants;
import com.mayuanfei.springboot14.pojo.UserInfo;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 用户缓存测试
 *
 * @author 老马
 * @date 2023-07-10 16:23
 */
@RestController
public class UserCacheTestController {

    @Resource
    private HazelcastInstance hazelcastInstance;

    @PostMapping(value = "/writeuser")
    public String writeDataToHazelcast(String userId, String userName, Integer liveTime) {
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(userId);
        userInfo.setUserName(userName);
        IMap<String, String> map = hazelcastInstance.getMap(Constants.CACHE_NAME_SESSION_USERS);
        if(null != liveTime && liveTime > 0){
            map.put(userId, JSONUtil.toJsonStr(userInfo), liveTime, TimeUnit.SECONDS);
        }else {
            map.put(userId, JSONUtil.toJsonStr(userInfo));
        }
        return "Map数据写入完成" + JSONUtil.toJsonStr(map.get(userId));
    }

    @GetMapping(value = "/readoneuser")
    @Cacheable(cacheNames = "session:users", key = "#userId", condition = "#userId != null")
    public String readDataFromHazelcast(String userId) {
        Map<String, String> hazelcastMap = hazelcastInstance.getMap(Constants.CACHE_NAME_SESSION_USERS);
        return hazelcastMap.get(userId);
    }

    @GetMapping(value = "/readalluser")
    public Map<String, String> readAllDataFromHazelcast() {
        return hazelcastInstance.getMap(Constants.CACHE_NAME_SESSION_USERS);
    }

}